package logic

import (
	"context"
	"encoding/json"
	"gozerogateway/rpc/tenant/app"
	"gozerogateway/rpc/tenant/internal/svc"
	"gozerogateway/rpc/tenant/tenantclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type AppListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAppListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AppListLogic {
	return &AppListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AppListLogic) AppList(in *tenantclient.AppListReq) (*tenantclient.AppListResp, error) {
	// todo: add your logic here and delete this line

	all, err := l.svcCtx.AppModel.FindAll(l.ctx, in, in.PageNo, in.PageSize) //Pageno Current
	count, _ := l.svcCtx.AppModel.Count(l.ctx)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("分页查询所有app信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	var outList []*app.AppListItemResp
	for _, applist := range *all {
		//appDetail, err := l.ServiceDetail(&applist)  //some table search together
		//if err != nil {
		//	logx.WithContext(l.ctx).Errorf("")
		//	return nil, err
		//}

		realQps := int64(0)
		realQpd := int64(0)
		outItem := &app.AppListItemResp{ //& not&
			ID:       applist.Id,
			AppID:    applist.AppId,
			Name:     applist.Name,
			Secret:   applist.Secret, //负载类型 0=http 1=tcp 2=grpc
			WhiteIPS: applist.WhiteIps,
			Qps:      applist.Qps,
			Qpd:      applist.Qpd,
			RealQpd:  realQpd,
			RealQps:  realQps,
		}
		outList = append(outList, outItem)
	}

	reqStr, _ := json.Marshal(in)
	listStr, _ := json.Marshal(outList)
	logx.WithContext(l.ctx).Infof("分页查询所有app信息,参数：%s,响应：%s", reqStr, listStr)

	return &tenantclient.AppListResp{
		Total: count,
		List:  outList,
	}, nil
}
